package com.example.dreamlist2.goal;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dreamlist2.StateInfo;

import com.example.dreamlist2.R;
import com.kongzue.takephoto.TakePhotoUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class HabitCompleteActivity extends AppCompatActivity {

    StateInfo stateInfo;

    TextView get_gps;
    EditText feeling;
    String feeling_content;
    ImageView photo_add;
    HabitCompleteItem habitCompleteItem;
    TextView ok;
    String location;
    Date date;
    Integer Year, Month, Day, Hour, Minute;
    private File imagePath;
    private final static int REQUEST_CAMERA = 123;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.habit_complete);
        get_gps = findViewById(R.id.habit_list_text_gps);
        feeling = findViewById(R.id.habit_list_cont_feeling);
        photo_add = findViewById(R.id.habit_list_img_photo_add);
        ok = findViewById(R.id.habit_list_text_ok);
        mImageView = findViewById(R.id.i_mageView);

        habitCompleteItem = new HabitCompleteItem();

        stateInfo = (StateInfo)getApplication();

        Calendar mcalendar = Calendar.getInstance();     //  获取当前时间    —   年、月、日
        Year = mcalendar.get(Calendar.YEAR);         //  得到当前年
        Month = mcalendar.get(Calendar.MONTH);       //  得到当前月
        Day = mcalendar.get(Calendar.DAY_OF_MONTH);  //  得到当前日
        Hour  = mcalendar.get(Calendar.HOUR_OF_DAY);    //得到小时
        Minute  = mcalendar.get(Calendar.MINUTE);            //得到分钟

        //初始化
        GetPhotoUtil.ALLOW_MULTIPLE = false;                               //是否允许多选图片
        GetPhotoUtil.COMPRESSED_PICS = true;                               //是否开启压缩
        GetPhotoUtil.DEFAULT_QUALITY = 90;                                 //压缩框架：图片质量
        GetPhotoUtil.DEFAULT_MAX_WIDTH = 1080;                             //压缩框架：图片最大宽度
        GetPhotoUtil.DEFAULT_MAX_HEIGHT = 1080;                            //压缩框架：图片最大高度
        GetPhotoUtil.DEFAULT_PIC_TYPE = Bitmap.CompressFormat.JPEG;        //压缩框架：默认压缩格式

        //获取gps
        get_gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(HabitCompleteActivity.this, GpsActivity.class),0x1);
            }
        });

        //回调逻辑
        GetPhotoUtil.getInstance(HabitCompleteActivity.this).setReturnPhoto(new GetPhotoUtil.ReturnPhoto() {

            @Override
            public void onGetPhotos(String[] selectImagePaths) {
                photo_add.setImageBitmap(GetPhotoUtil.getBitmapFromUri(HabitCompleteActivity.this,selectImagePaths[0]));
                //txtPath.setText(selectImagePaths[0]);

                Log.i(">>>", "onGetPhotos: ====================");
                for (String s : selectImagePaths) {
                    Log.i("+", s);
                }
                Log.i(">>>", "onGetPhotos: ====================");
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(HabitCompleteActivity.this, "发生错误，请在Logcat查看详情", Toast.LENGTH_SHORT);
                e.printStackTrace();
            }
        });

        //照片打卡
        photo_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showMenu();
                //openSystemCamera();
                /*
                // 从相册中选择
                Intent intent = new Intent(HabitCompleteActivity.this, TakePhotosActivity.class);
                intent.putExtra(TakePhotosActivity.TAKEPHOTO_TYPE,TakePhotosActivity.ON_SELECTPICTURES);
                startActivityForResult(intent, 0x2);

                 */

                stateInfo.setRecordin(habitCompleteItem);
                startActivityForResult(new Intent(HabitCompleteActivity.this, PicActivity.class),0x1);





            }
        });

        //确认并提交
        //打卡数据上传数据库
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feeling_content = feeling.getText().toString();
                submit_habitcomplet();
            }
        });
    }

    private void submit_habitcomplet() {
        habitCompleteItem = stateInfo.getRecordin();
        habitCompleteItem.setPos(location);
        habitCompleteItem.setFeeling(feeling_content);

        HabitItem habitItem = stateInfo.getHabitin();
        habitCompleteItem.setHid(habitItem.getObjectId());
        habitItem.addTimes();
        habitCompleteItem.setThis_time(habitItem.getTimes());
        habitCompleteItem.setUid(habitItem.getUid());
        habitCompleteItem.setHcont(habitItem.getContent());

        date = new Date();
        Month = Month + 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start_time = Year.toString()+"-"+Month.toString()+"-"+Day.toString()+" "
                +Hour.toString()+":"+Minute.toString()+":00";
        try {
            date = sdf.parse(start_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        BmobDate bdate = new BmobDate(date);
        habitCompleteItem.setDate(bdate);

        //stateInfo = (StateInfo)getApplication();

        habitItem.update(habitItem.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    Log.i("bmob","打卡事项次数加一");
                    //Toast.makeText(HabitCompleteActivity.this, "打卡成功！", Toast.LENGTH_SHORT);
                    setResult(1);
                    finish();
                }else{
                    Log.i("bmob","打卡事项次数更新失败："+e.getMessage()+","+e.getErrorCode());
                    //Toast.makeText(HabitCompleteActivity.this, "打卡失败……", Toast.LENGTH_SHORT);
                }
            }
        });

        habitCompleteItem.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    Log.i("bmob","新建打卡记录成功");
                    Toast.makeText(HabitCompleteActivity.this, "打卡成功！", Toast.LENGTH_SHORT);
                    setResult(1);
                    finish();
                }else{
                    Log.i("bmob","新建打卡记录失败："+e.getMessage()+","+e.getErrorCode());
                    Toast.makeText(HabitCompleteActivity.this, "打卡失败……", Toast.LENGTH_SHORT);
                }
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        //如果data等于null返回
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        location = data.getStringExtra("location");
        if (requestCode == 1) {
            get_gps.setText(location);
            get_gps.setTextColor(Color.BLACK);
            TextPaint tp = get_gps.getPaint();
            tp.setFakeBoldText(true);
        }
        if(requestCode == 2) {
            photo_add.setImageDrawable(getResources().getDrawable(R.drawable.avatar));
        }
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            Glide.with(this).load(imagePath).into(mImageView);
        }
        //GetPhotoUtil.getInstance(HabitCompleteActivity.this).onActivityResult(requestCode, resultCode, data);

    }

    private void showMenu() {
        String[] selectShunxuStr = new String[]{"使用相机拍摄", "从相册中选择", "取消"};
        new AlertDialog.Builder(this).setItems(selectShunxuStr, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        // 拍照
                        openSystemCamera();
                        /*
                        Intent intent = new Intent(HabitCompleteActivity.this, TakePhotosActivity.class);
                        intent.putExtra(TakePhotosActivity.TAKEPHOTO_TYPE,TakePhotosActivity.ON_TAKEPHOTOS);
                        startActivityForResult(intent, 2);

                         */
                        //photo_add.setImageDrawable(getResources().getDrawable(R.drawable.avatar));
                        //tPhotoUtil.getInstance(HabitCompleteActivity.this).doOpenCamera();
                        break;
                    case 1:
                        GetPhotoUtil.getInstance(HabitCompleteActivity.this).doOpenGallery();
                        photo_add.setImageDrawable(getResources().getDrawable(R.drawable.avatar));
                        break;
                    case 2:
                        //photo_add.setImageDrawable(null);
                        //txtPath.setText("");
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 打开系统相机
     */
    private void openSystemCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String imageName = String.format(Locale.getDefault(), "img_%d.jpg", System.currentTimeMillis());
        imagePath = new File(getExternalFilesDir(""), imageName);
        Uri outUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", imagePath);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        startActivityForResult(cameraIntent, REQUEST_CAMERA);
    }

}